import React, { useCallback, useRef, useState } from 'react';
import { Button, Drawer, Form, Input, message, Select, Space } from 'antd';
import { ProTable, ProColumns } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { fetchAgreementList, createAgreement, updateAgreement, deleteAgreement} from '@/services/ant-design-pro/agreement';
import type { ActionType } from '@ant-design/pro-components';
import RichTextEditor from '@/components/RichTextEditor';
import FileUpload from '@/components/FileUpload';

const { Option } = Select;

const AgreementList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [currentRecord, setCurrentRecord] = useState<any | undefined>(undefined);
  const [form] = Form.useForm();
  const { run: delRun, loading: deleteLoading } = useRequest(deleteAgreement, {
    manual: true,
    onSuccess: () => {
      actionRef.current?.reload();
      message.success('删除成功');
    },
    onError: () => {
      message.error('删除失败，请重试');
    },
  });

  const { run: createRun } = useRequest(createAgreement, {
    manual: true,
    onSuccess: () => {
      actionRef.current?.reload();
      message.success('创建成功');
    },
    onError: () => {
      message.error('创建失败，请重试');
    },
  });

  const { run: updateRun } = useRequest(updateAgreement, {
    manual: true,
    onSuccess: () => {
      actionRef.current?.reload();
      message.success('更新成功');
    },
    onError: () => {
      message.error('更新失败，请重试');
    },
  });

  const handleRemove = useCallback(
    async (selectedRows: any[]) => {
      if (selectedRows.length === 0) {
        message.warning('请先选择要删除的项');
        return;
      }
      await delRun({ id: selectedRows.map((row) => row.id)[0] });
    },
    [delRun],
  );

  const handleSave = useCallback(
    async (values: any) => {
      if (currentRecord) {
        await updateRun({ ...currentRecord, ...values });
      } else {
        await createRun(values);
      }
      setDrawerVisible(false);
    },
    [currentRecord, createRun, updateRun],
  );

  const columns: ProColumns<any>[] = [
    {
      title: '协议类型',
      dataIndex: 'typeName',
      width: 150,
      ellipsis: true,
    },
    // {
    //   title: '类型',
    //   dataIndex: 'type',
    //   width: 100,
    //   ellipsis: true,
    //   render: (text) => {
    //     switch (text) {
    //       case 1:
    //         return '隐私协议';
    //       case 2:
    //         return '用户协议';
    //       case 3:
    //         return '服务说明';
    //       default:
    //         return '';
    //     }
    //   },
    // },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
      ellipsis: true,
    },
    {
      title: '操作',
      width: 180,
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentRecord(record);
            form.setFieldsValue(record);
            setDrawerVisible(true);
          }}
        >
          编辑
        </a>
      ],
    },
  ];

  return (
    <>
      <ProTable<any>
        headerTitle="协议管理列表"
        actionRef={actionRef}
        rowKey="id"
        search={false}
        // toolBarRender={() => [
        //   <Button
        //     key={'new'}
        //     type="primary"
        //     onClick={() => {
        //       setCurrentRecord(undefined);
        //       form.resetFields();
        //       setDrawerVisible(true);
        //     }}
        //   >
        //     新建
        //   </Button>,
        // ]}
    
        request={(params) => fetchAgreementList(params)}
        columns={columns}
      />

      <Drawer
        title={currentRecord ? '协议详情' : '新建协议'}
        width={600}
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        footer={
          <Space>
            <Button onClick={() => setDrawerVisible(false)}>取消</Button>
            <Button
              type="primary"
              onClick={() => {
                form.validateFields().then(handleSave);
              }}
            >
              提交
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical" initialValues={currentRecord}>
          <Form.Item
            name="type"
            label="类型"
            rules={[{ required: true, message: '请选择类型' }]}
          >
            <Select placeholder="请选择类型">
              <Option value={1}>隐私协议</Option>
              <Option value={2}>用户协议</Option>
              <Option value={3}>服务说明</Option>
              <Option value={4}>合同范本</Option>
              <Option value={5}>注册协议</Option>
              <Option value={6}>个人信息处理规则</Option>
              <Option value={7}>对公彰化信息</Option>
            </Select>
          </Form.Item>
          {(currentRecord?.type===4&&
          <>
          <Form.Item label="上传文件" name="url">
          <FileUpload value={form.getFieldValue('url')} onChange={(url) => form.setFieldsValue({ attachment: url })} />
          </Form.Item>
          </>)}
          
          {(currentRecord?.type===7&&<>
          <Form.Item
            name="bank"
            label="银行名称"
          >
            <Input placeholder="请输入银行名称" />
          </Form.Item>
          <Form.Item
            name="account"
            label="银行账号"
          >
            <Input placeholder="请输入银行账号" />
          </Form.Item>
          </>)}
          
          {(currentRecord?.type!==4&&<>
            <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: '请输入内容' }]}
          >
            <RichTextEditor value={form.getFieldValue('content')} onChange={(value) => form.setFieldsValue({ content: value })} />
          </Form.Item>
          </>)}
      
        </Form>
      </Drawer>
    </>
  );
};

export default AgreementList;